package com.example.controller;

import com.example.Utils.MD5Utils;
import com.example.models.User;
import com.google.gson.Gson;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
public class InterfaceController {

    @RequestMapping(value = "/user_register/",method = RequestMethod.POST)
    @ResponseBody
    public String userRegister(HttpServletRequest request){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String pic = request.getParameter("pic_path");
        System.out.println("userName: "+username);
        List<User> userList = User.search().eq("username",username).findList();
        Map<String,String> resMap = new HashMap<>();
        if(userList.size() != 0){
            resMap.put("status","repeat");
            return new Gson().toJson(resMap);
        }
        User user = new User();
        user.username = username;
        user.password = MD5Utils.MD5Encode(password,"utf-8");
        user.headImgPath = pic;
        user.save();
        resMap.put("status","success");
        return new Gson().toJson(resMap);
    }

    @RequestMapping(value = "/user_login_verify/",method = RequestMethod.POST)
    @ResponseBody
    public String userLoginVerify(HttpServletRequest request){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Map<String,String> resMap = new HashMap<>();
        User user = User.search().eq("username",username).eq("isAdmin",false).findOne();
        if(user == null){
            resMap.put("status","error");
            resMap.put("msg","invalid username or password");
            return new Gson().toJson(resMap);
        }
        String realPassword = MD5Utils.MD5Encode(password,"utf-8");
        if(realPassword.equals(user.password)){
            resMap.put("status","success");
            resMap.put("username",username);
            resMap.put("password",password);
            resMap.put("user_id",user.id.toString());
            user.setLastLogin(new Date());
            resMap.put("user_img",user.headImgPath);
            user.save();
            return new Gson().toJson(resMap);
        }
        resMap.put("status","error");
        resMap.put("msg","error password");
        return new Gson().toJson(resMap);
    }
}
